﻿Library.UserInterface.Widgets.RssReader = function (options) {
    var defaults = {
        container: null,
        feedSource: "",
        limit: 20,        
        target: "_blank",
        showDate: true,
        interval: 15000,        
        titleSelector: "",
        onSettingsSave: ""
    };
    var options = $.extend(defaults, options);

    this.container = options.container;
    this.feedSource = options.feedSource;
    this.limit = options.limit;    
    this.target = options.target;
    this.showDate = options.showDate;
    this.interval = options.interval;        
    this.titleSelector = options.titleSelector;
    this.onSettingsSave = options.onSettingsSave;

    this.initialize(false);
}

Library.UserInterface.Widgets.RssReader.prototype = {
    container: null,
    feedSource: "",
    limit: 20,    
    target: "_blank",
    showDate: true,
    interval: 15000,    
    titleSelector: "",
    onSettingsSave: "",
    items: [],
    api: "",
    fullscreen: false,
    minimize: true,
    settings: true,
    id: null,
    type: "widget.rssreader",

    initialize: function (set) {
        if (this.id != null)
            Library.UserInterface.Widgets.Dispose(this.id);

        this.id = Library.Util.ReplaceAll(Library.Crypto.Guid(), "-", "");
        this.container.find(".portlet-widget").html(Library.UserInterface.Widgets.RssReader.Lang.loading);

        Library.UserInterface.Widgets.Add(this);

        if (this.titleSelector == "")
            this.titleSelector = this.container.find(".portlet-title").selector;

        if (this.titleSelector != "")
            $(this.titleSelector).html(Library.UserInterface.Widgets.RssReader.Lang.loading);

        if (set) {
            this.container.find(".portlet-widget").toggle("blind", {}, 500);
            this.container.find(".portlet-widget").parents(".portlet-content").find(".portlet-settings").toggle("blind", {}, 500);
        }

        if (!this.container.find(".portlet-widget").hasClass('rssFeed'))
            this.container.addClass('rssFeed');
        if (this.feedSource == null) {
            this.container.find(".portlet-widget").html(Library.UserInterface.Widgets.RssReader.Lang.feedSourceException);
            return;
        }

        var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(this.feedSource);
        if (this.limit != null)
            api += "&num=" + this.limit;
        api += "&output=json_xml";
        this.api = api;

        var widget = this;
        $(document).everyTime(this.interval, this.id, function (i) {
            $.getJSON(api, function (data) {
                try {
                    if (data.responseStatus == 200) {
                        var feeds = data.responseData.feed
                        if (!feeds) {
                            return false;
                        }
                        var desc = feeds.title;
                        var entries = $(feeds.entries).sort(function (a, b) { return parseFloat(dateFormat(a.publishedDate, 'yyyymmddHHMM')) - parseFloat(dateFormat(b.publishedDate, 'yyyymmddHHMM')) });

                        for (var i = 0; i < entries.length; i++) {
                            widget.addItem(entries[i]);
                        }

                        if (widget.titleSelector == "")
                            $("<div class=\"RssHeader\">" + Library.Util.ReplaceAll(Library.UserInterface.Widgets.RssReader.Lang.title, "{0}", desc) + "</div>").prependTo(widget.container.find(".portlet-widget"));
                        else
                            $(widget.titleSelector).html(Library.Util.ReplaceAll(Library.UserInterface.Widgets.RssReader.Lang.title, "{0}", desc));

                        widget.container.find(".RssItem").showdelay({ delay: 400, fadeinMillis: 1200 });
                    } else {                        
                        Library.UserInterface.Widgets.Error(widget.id, data.responseDetails); 
                    }
                } catch (err) {
                    Library.UserInterface.Widgets.Error(widget.id, err); 
                }
            });
        });
        Library.UserInterface.Widgets.SetHeaderIcons(this);
        this.getSettings();
    },

    addItem: function (entry) {
        if (this.items == null || this.items.length == 0)
            this.container.find(".portlet-widget").html("");

        if (entry == null)
            return;

        var token = Library.Crypto.Md5(entry.title + entry.publishedDate + entry.contentSnippet);
        if (Library.Array.Contains(this.items, token))
            return;

        this.items = Library.Array.Add(this.items, token);

        html = "";
        html += "<div class=\"RssItem " + token + "\" style=\"display:none\">";
        html += "<div class=\"RssTitle\">" + entry.title + "</div>";
        if (this.showDate)
            html += "<div class=\"RssDate\">" + dateFormat(entry.publishedDate, Library.UserInterface.Widgets.RssReader.Lang.dateFormat) + "</div>";
        html += "<div class=\"RssContent\">" + entry.contentSnippet + "<a href=\"" + entry.link + "\" target=\"" + this.target + "\"> " + Library.UserInterface.Widgets.RssReader.Lang.readMore + "</a></div>";
        html += "</div>";
        $(html).prependTo(this.container.find(".portlet-widget"));
    },

    getSettings: function () {
        var settingsHTML = "";
        try {
            settingsHTML += "<table class=\"Forms\"><tr><td class=\"Standart\">" + Library.UserInterface.Widgets.RssReader.Lang.feedSource + "</td><td>";
            settingsHTML += "<select class=\"ui-feed-source\">";
            $.get("/Util/ParameterXml.aspx", { TableName: "PORTLET_RSS" },
            function (data) {
                try {
                    data = $($(data)[1]);
                    var fSource = "";
                    var len = data.find("parametre").length;
                    for (var xd = 0; xd < len; xd++) {
                        fSource += "<option value=\"" + $(data.find("parametre")[xd]).find("alan1")[0].childNodes[0].data + "\">" + $(data.find("parametre")[xd]).find("aciklama")[0].childNodes[0].data + "</option>";
                    }
                } catch (err) {
                    fSource = err;
                }
                $(".ui-feed-source").html(fSource);
            },
            function (a, b, c) { });
            settingsHTML += "</select>";
            settingsHTML += "</td><td class=\"Buttons\">";
            settingsHTML += "<input type=\"button\" value=\"" + Library.UserInterface.Widgets.RssReader.Lang.save + "\" style=\"font-size:12px; width:60px\" onclick=\"Library.UserInterface.Widgets.Get('" + this.id + "').save()\"/>";
            settingsHTML += "</td></tr></table>";
            this.container.find(".portlet-settings").html(settingsHTML);
        } catch (err) {
            Library.UserInterface.Widgets.Error(this.id, err); 
        }
    },

    save: function () {
        this.feedSource = this.container.find(".ui-feed-source").val();
        this.items = [];
        $(document).stopTime(this.id);

        if (jQuery.isFunction(this.onSettingsSave))
            eval(this.onSettingsSave + "('" + this.feedSource + "')");

        this.initialize(true);
    }
}